Python更新YAML而不更改格式 您所在的位置:网站首页 yaml 双引号 单引号 Python更新YAML而不更改格式

Python更新YAML而不更改格式

2023-11-07 08:37| 来源: 网络整理| 查看: 265

您可能忽略了输出值中的引号从单引号更改为双引号。默认情况下,ruamel.yaml不会尝试保留引号,因此可以删除任何多余的引号,或者在本例中使用更紧凑的表示。使用双引号,不需要在标量内复制单引号。

您可以通过设置.preserve_quotes属性来保留引号:

import sys from ruamel.yaml import YAML yaml = YAML() yaml.preserve_quotes = True with open('test.yaml') as f: test = yaml.load(f) test['sso']['version'] = '1.0.1' yaml.dump(test, sys.stdout)

这就给出了:

sso: version: 1.0.1 configs: - configName: config1.conf fileContent: 'startDelaySeconds: 0 lowercaseOutputName: true lowercaseOutputLabelNames: false whitelistObjectNames: [''org.apache.commons.pool2:*''] blacklistObjectNames: [] rules: - pattern: ".*" '

我建议考虑对包含换行符的值使用文字样式标量,因为在这些值中,您不需要将换行符加倍,也不需要在标量中使用双引号:

yaml_str = """ sso: version: 1.0.0 configs: - configName: config1.conf fileContent: | startDelaySeconds: 0 lowercaseOutputName: true lowercaseOutputLabelNames: false whitelistObjectNames: ['org.apache.commons.pool2:*'] blacklistObjectNames: [] rules: - pattern: ".*" """ import sys from ruamel.yaml import YAML yaml = YAML() yaml.preserve_quotes = True with open('test.yaml') as f: test = yaml.load(f) data = yaml.load(yaml_str) assert data['sso']['configs'][0]['fileContent'] == test['sso']['configs'][0]['fileContent']


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有